package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.GroupHorizontalAdapter;
import com.hxkcloud.patient.beans.DepartmentBean;
import com.hxkcloud.patient.beans.DoctorGroupBean;
import com.hxkcloud.patient.beans.HospitalStatusBean;
import com.hxkcloud.patient.beans.PatientInfoBean;
import com.hxkcloud.patient.dborm.DepartmentDao;
import com.hxkcloud.patient.dborm.DoctorGroupDao;
import com.hxkcloud.patient.dborm.HospitalStatusDao;
import com.hxkcloud.patient.popup.GroupSelectorPopWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.UrlAddress;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.ImageUtil;
import com.hxkcloud.patient.utils.StringUtil;

import java.util.List;

/**
 * Created by william_sun on 2016-07-07.
 * Description:患者信息
 */
public class PatientInfoActivity extends BaseActivity implements View.OnClickListener {

    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private ImageView iv_edit;

    //info
    private TextView tv_name;
    private TextView tv_age;
    private TextView tv_sex;
    private LinearLayout ll_tel;
    private TextView tv_tel;
    private Button bt_inhospital;
    private Button bt_assessrecord;
    private Button bt_historyrecord;

    //symptom
    private LinearLayout ll_symptom_whole;
    private LinearLayout ll_symptom_title;
    private ImageView iv_symptom_arrow;
    private LinearLayout ll_symptom;

    //basicinfo
    private LinearLayout ll_basicinfo_whole;
    private LinearLayout ll_basicinfo_title;
    private ImageView iv_basicinfo_arrow;
    private LinearLayout ll_basicinfo;

    //oldhistory
    private LinearLayout ll_oldhistory_whole;
    private LinearLayout ll_oldhistory_title;
    private ImageView iv_oldhistory_arrow;
    private LinearLayout ll_oldhistory;

    //group
    private LinearLayout ll_group;
    private TextView tv_group;

    private boolean isSymptomShow = false;
    private boolean isBasicinfoShow = false;
    private boolean isOldhistoryShow = false;

    private PopupWindow popup_func;//右上角操作框
    private TextView tv_symptom;
    private View view_func1;
    private TextView tv_basicinfo;
    private View view_func2;
    private TextView tv_oldhistory;

    private String patientId = "";//患者ID
    private PatientInfoBean patientInfo;

    private List<HospitalStatusBean> hospitalStatus;

    private boolean isChanke;

    private List<DoctorGroupBean> groups;

    private GroupSelectorPopWindow groupSelectorPopWindow;
    private String newGroupId = "";

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_PATIENTINFO_SUCCESS:
                patientInfo = (PatientInfoBean) msg.obj;
                showDate();
                break;
            case MessageCode.NETWORKCODE_PATIENTINFO_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(getResources().getString(R.string.patientinfogetfail));
                }
                break;
            case MessageCode.NETWORKCODE_USERJOINDOCTORGROUP_SUCCESS:
                for (DoctorGroupBean group : groups) {
                    if (group.getGroupId().equals(newGroupId)) {
                        tv_group.setText(group.getName());
                        patientInfo.setGroupId(newGroupId);
                    }
                }
                break;
            case MessageCode.NETWORKCODE_USERJOINDOCTORGROUP_FAILURE:
                if (msg.obj != null) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.userjoingroupfail);
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patientinfo);

        patientId = this.getIntent().getStringExtra("patientId");
        if (TextUtils.isEmpty(patientId)) {
            finish();
        }
        HospitalStatusDao hospitalStatusDao = new HospitalStatusDao(mContext);
        hospitalStatus = hospitalStatusDao.getHospitalStatus(StringUtil.isCurChanke(loginInfo.getDepartmentId(), mContext));

        initView();
        initPopup();
        loading();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        iv_edit = (ImageView) findViewById(R.id.iv_title_func);

        tv_name = (TextView) findViewById(R.id.tv_patientinfo_name);
        tv_age = (TextView) findViewById(R.id.tv_patientinfo_age);
        tv_sex = (TextView) findViewById(R.id.tv_patientinfo_sex);
        ll_tel = (LinearLayout) findViewById(R.id.ll_patientinfo_tel);
        tv_tel = (TextView) findViewById(R.id.tv_patientinfo_tel);
        bt_inhospital = (Button) findViewById(R.id.bt_patientinfo_inhospital);
        bt_assessrecord = (Button) findViewById(R.id.bt_patientinfo_assessrecord);
        bt_historyrecord = (Button) findViewById(R.id.bt_patientinfo_historyrecord);

        ll_symptom_whole = (LinearLayout) findViewById(R.id.ll_patientinfo_symptom_whole);
        ll_symptom_title = (LinearLayout) findViewById(R.id.ll_patientinfo_symptom_title);
        iv_symptom_arrow = (ImageView) findViewById(R.id.iv_patientinfo_symptom_arrow);
        ll_symptom = (LinearLayout) findViewById(R.id.ll_patientinfo_symptom);
        ll_basicinfo_whole = (LinearLayout) findViewById(R.id.ll_patientinfo_basicinfo_whole);
        ll_basicinfo_title = (LinearLayout) findViewById(R.id.ll_patientinfo_basicinfo_title);
        iv_basicinfo_arrow = (ImageView) findViewById(R.id.iv_patientinfo_basicinfo_arrow);
        ll_basicinfo = (LinearLayout) findViewById(R.id.ll_patientinfo_basicinfo);
        ll_oldhistory_whole = (LinearLayout) findViewById(R.id.ll_patientinfo_oldhistory_whole);
        ll_oldhistory_title = (LinearLayout) findViewById(R.id.ll_patientinfo_oldhistory_title);
        iv_oldhistory_arrow = (ImageView) findViewById(R.id.iv_patientinfo_oldhistory_arrow);
        ll_oldhistory = (LinearLayout) findViewById(R.id.ll_patientinfo_oldhistory);
        ll_group = (LinearLayout) findViewById(R.id.ll_patientinfo_group_title);
        tv_group = (TextView) findViewById(R.id.tv_patientinfo_group_group);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText(getResources().getText(R.string.patientinfo));
        iv_edit.setVisibility(View.VISIBLE);
        iv_edit.setOnClickListener(this);
        iv_edit.setPadding(0, 0, 0, 0);

        ll_tel.setOnClickListener(this);
        bt_inhospital.setOnClickListener(this);
        bt_assessrecord.setOnClickListener(this);
        bt_historyrecord.setOnClickListener(this);

        ll_symptom_title.setOnClickListener(this);
        ll_basicinfo_title.setOnClickListener(this);
        ll_oldhistory_title.setOnClickListener(this);
        ll_group.setOnClickListener(this);

        isChanke = false;
        if ((loginInfo != null) && (!TextUtils.isEmpty(loginInfo.getDepartmentId()))) {
            DepartmentDao departmentDao = new DepartmentDao(mContext);
            List<DepartmentBean> dbs = departmentDao.getDepartment();
            for (DepartmentBean d : dbs) {
                if (d.getDepartmentId() == Integer.valueOf(loginInfo.getDepartmentId())) {
                    if (d.getType().equals("0")) {//产科
                        isChanke = true;
                        break;
                    }
                }
            }
        }

        if (isChanke) {
            ll_symptom_whole.setVisibility(View.GONE);
            ll_basicinfo_whole.setVisibility(View.VISIBLE);
            ll_oldhistory_whole.setVisibility(View.GONE);
            bt_assessrecord.setVisibility(View.GONE);
        } else {
            ll_symptom_whole.setVisibility(View.VISIBLE);
            ll_basicinfo_whole.setVisibility(View.VISIBLE);
            ll_oldhistory_whole.setVisibility(View.VISIBLE);
        }

        DoctorGroupDao doctorGroupDao = new DoctorGroupDao(mContext);
        groups = doctorGroupDao.getGroup();
    }

    private void initPopup() {
        popup_func = new PopupWindow(this);
        View viewFunc = LayoutInflater.from(this).inflate(R.layout.popup_patientinfo_func, null);
        popup_func.setContentView(viewFunc);

        popup_func.setWidth(screenWidth / 3);
        popup_func.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_func.setFocusable(true);
        popup_func.setTouchable(true);
        popup_func.setOutsideTouchable(true);
        popup_func.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_func.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_symptom = (TextView) viewFunc.findViewById(R.id.tv_patientinfo_func1);
        tv_basicinfo = (TextView) viewFunc.findViewById(R.id.tv_patientinfo_func2);
        tv_oldhistory = (TextView) viewFunc.findViewById(R.id.tv_patientinfo_func3);
        view_func1 = viewFunc.findViewById(R.id.view_patientinfo_func1);
        view_func2 = viewFunc.findViewById(R.id.view_patientinfo_func2);

        tv_symptom.setOnClickListener(this);
        tv_basicinfo.setOnClickListener(this);
        tv_oldhistory.setOnClickListener(this);

        popup_func.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(PatientInfoActivity.this);
            }
        });

        if (isChanke) {
            tv_symptom.setVisibility(View.GONE);
            tv_oldhistory.setVisibility(View.GONE);
            view_func1.setVisibility(View.GONE);
            view_func2.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

        YiJiaHuNetWorkUtils.getPatientInfo(patientId, handler);
    }

    private void showDate() {
        if (patientInfo != null) {
            tv_name.setText(patientInfo.getName());
//            tv_age.setText(patientInfo.getAge() + "岁");
            if (patientInfo.getAge().equals("0")) {
                tv_age.setText("<1岁");
            } else {
                tv_age.setText(patientInfo.getAge() + "岁");
            }
            if (patientInfo.getSex().equals("0")) {
                tv_sex.setText(R.string.male);
            } else if (patientInfo.getSex().equals("1")) {
                tv_sex.setText(R.string.female);
            } else {
                tv_sex.setText(R.string.unknown);
            }
            tv_tel.setText(patientInfo.getTel());

            //hospital status
            for (HospitalStatusBean status : hospitalStatus) {
                if (patientInfo.getHospitalStatus().equals(status.getItemId())) {
                    bt_inhospital.setText(status.getName());
                    break;
                }
            }


            if (patientInfo.getSymptom() != null && patientInfo.getSymptom().size() > 0) {
//                ll_symptom_whole.setVisibility(View.VISIBLE);
                ll_symptom.removeAllViews();
                for (PatientInfoBean.PatientInfoIntroBean intro : patientInfo.getSymptom()) {
                    addIntro(ll_symptom, intro.getName(), intro.getInfo());
                }
            } else {
//                ll_symptom_whole.setVisibility(View.GONE);
            }
            if (patientInfo.getBasicinfo() != null && patientInfo.getBasicinfo().size() > 0) {
//                ll_basicinfo_whole.setVisibility(View.VISIBLE);
                ll_basicinfo.removeAllViews();
                for (PatientInfoBean.PatientInfoIntroBean intro : patientInfo.getBasicinfo()) {
                    addIntro(ll_basicinfo, intro.getName(), intro.getInfo());
                }
            } else {
//                ll_basicinfo_whole.setVisibility(View.GONE);
            }
            if (patientInfo.getHistory() != null && patientInfo.getHistory().size() > 0) {
//                ll_oldhistory_whole.setVisibility(View.VISIBLE);
                ll_oldhistory.removeAllViews();
                for (PatientInfoBean.PatientInfoIntroBean intro : patientInfo.getHistory()) {
                    addIntro(ll_oldhistory, intro.getName(), intro.getInfo());
                }
            } else {
//                ll_oldhistory_whole.setVisibility(View.GONE);
            }

//            patientInfo.setGroupId("4");
            if (!TextUtils.isEmpty(patientInfo.getGroupId())) {
                for (DoctorGroupBean group : groups) {
                    if (group.getGroupId().equals(patientInfo.getGroupId())) {
                        tv_group.setText(group.getName());
                    }
                }
            }
        }
    }

    //页面添加数据
    private void addIntro(LinearLayout ll, String name, String info) {


        View view = new View(mContext);
        LinearLayout.LayoutParams lp_view = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ImageUtil.dip2px(3, mContext));
        lp_view.topMargin = ImageUtil.dip2px(8, mContext);
        lp_view.bottomMargin = ImageUtil.dip2px(8, mContext);
        view.setLayoutParams(lp_view);
        view.setBackgroundResource(R.drawable.divider_dash);
        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//关闭硬件加速

        TextView tv_name = new TextView(mContext);
        LinearLayout.LayoutParams lp_tv1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        tv_name.setLayoutParams(lp_tv1);
        tv_name.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
        tv_name.setText("【" + name + "】");

        LinearLayout.LayoutParams lp_tv2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp_tv2.topMargin = ImageUtil.dip2px(10, mContext);
        TextView tv_info = new TextView(mContext);
        tv_info.setLayoutParams(lp_tv2);
        tv_info.setLineSpacing(ImageUtil.dip2px(5, mContext), 1);
        tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.black_text));
        tv_info.setText(info);

        ll.addView(view);
        if (!TextUtils.isEmpty(name)) {
            ll.addView(tv_name);
        }
        ll.addView(tv_info);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.iv_title_func:
                if (isChanke) {
                    String title2 = getResources().getString(R.string.basicinfo);
                    String url2 = UrlAddress.H5_EDITBASIC_URL + "&userInfoId=" + patientId + "&departmentId=" + loginInfo.getDepartmentId();
                    Intent iFunc2 = new Intent(mContext, WebActivity.class);
                    iFunc2.putExtra("title", title2);
                    iFunc2.putExtra("url", url2);
                    startActivity(iFunc2);
                } else {
                    popup_func.showAsDropDown(iv_edit, 0, ImageUtil.dip2px(10, mContext));
//                    BrightnessUtils.lightOff(PatientInfoActivity.this);
                }
                break;
            case R.id.ll_patientinfo_tel:
                if (patientInfo != null && !TextUtils.isEmpty(patientInfo.getTel())) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_CALL);
                    intent.setData(Uri.parse("tel:" + patientInfo.getTel()));
                    startActivity(intent);
                }
                break;
            case R.id.bt_patientinfo_inhospital:
                Intent iStatus = new Intent(mContext, PatientStatusSelectActivity.class);
                iStatus.putExtra("status", patientInfo.getHospitalStatus());
                iStatus.putExtra("patientId", patientId);
                if (patientInfo.getCyMap() != null) {
                    if (!TextUtils.isEmpty(patientInfo.getCyMap().getCyId())) {
                        iStatus.putExtra("cyId", patientInfo.getCyMap().getCyId());
                    }
                    if (!TextUtils.isEmpty(patientInfo.getCyMap().getCyTime())) {
                        iStatus.putExtra("cyTime", patientInfo.getCyMap().getCyTime());
                    }
                }
                if (patientInfo.getFzMap() != null) {
                    if (!TextUtils.isEmpty(patientInfo.getFzMap().getFzId())) {
                        iStatus.putExtra("fzId", patientInfo.getFzMap().getFzId());
                    }
                    if (!TextUtils.isEmpty(patientInfo.getFzMap().getFzTime())) {
                        iStatus.putExtra("fzTime", patientInfo.getFzMap().getFzTime());
                    }
                }
                startActivityForResult(iStatus, 0);
                break;
            case R.id.bt_patientinfo_assessrecord:
                Intent iAssess = new Intent(mContext, AssessRecordListActivity.class);
                iAssess.putExtra("patientId", patientId);
                iAssess.putExtra("patientName", patientInfo.getName());
                startActivity(iAssess);
                break;
            case R.id.bt_patientinfo_historyrecord:
                if (isChanke) {
                    StringUtil.zhugeTrack(mContext, "管理-患者信息-历史记录-基本信息", "历史记录基本信息查看数");

                    Intent iBasicinfo = new Intent(mContext, SymptomRecordActivity.class);
                    iBasicinfo.putExtra("type", 1);
                    iBasicinfo.putExtra("patientId", patientId);
                    startActivity(iBasicinfo);
                } else {
                    Intent iRecord = new Intent(mContext, HistoryRecordActivity.class);
                    iRecord.putExtra("patientId", patientId);
                    iRecord.putExtra("isChanke", isChanke);
                    startActivity(iRecord);
                }
                break;
            case R.id.ll_patientinfo_symptom_title:
                if (isSymptomShow) {
                    iv_symptom_arrow.setImageResource(R.mipmap.tab_arrow);
                    ll_symptom.setVisibility(View.GONE);
                    isSymptomShow = false;
                } else {
                    iv_symptom_arrow.setImageResource(R.mipmap.tab_arrow_up);
                    ll_symptom.setVisibility(View.VISIBLE);
                    isSymptomShow = true;
                }
                break;
            case R.id.ll_patientinfo_basicinfo_title:
                if (isBasicinfoShow) {
                    iv_basicinfo_arrow.setImageResource(R.mipmap.tab_arrow);
                    ll_basicinfo.setVisibility(View.GONE);
                    isBasicinfoShow = false;
                } else {
                    iv_basicinfo_arrow.setImageResource(R.mipmap.tab_arrow_up);
                    ll_basicinfo.setVisibility(View.VISIBLE);
                    isBasicinfoShow = true;
                }
                break;
            case R.id.ll_patientinfo_oldhistory_title:
                if (isOldhistoryShow) {
                    iv_oldhistory_arrow.setImageResource(R.mipmap.tab_arrow);
                    ll_oldhistory.setVisibility(View.GONE);
                    isOldhistoryShow = false;
                } else {
                    iv_oldhistory_arrow.setImageResource(R.mipmap.tab_arrow_up);
                    ll_oldhistory.setVisibility(View.VISIBLE);
                    isOldhistoryShow = true;
                }
                break;
            case R.id.tv_patientinfo_func1:
                popup_func.dismiss();
                String title1 = getResources().getString(R.string.symptom);
                String url1 = UrlAddress.H5_EDITSYMPTOM_URL + "&userInfoId=" + patientId + "&departmentId=" + loginInfo.getDepartmentId();
                Intent iFunc1 = new Intent(mContext, WebActivity.class);
                iFunc1.putExtra("title", title1);
                iFunc1.putExtra("url", url1);
                iFunc1.putExtra("functionback", true);
                iFunc1.putExtra("patientId", patientId);

                iFunc1.putExtra("patientInfoEdit", 1);
                startActivity(iFunc1);
                break;
            case R.id.tv_patientinfo_func2:
                popup_func.dismiss();
                String title2 = getResources().getString(R.string.basicinfo);
                String url2 = UrlAddress.H5_EDITBASIC_URL + "&userInfoId=" + patientId + "&departmentId=" + loginInfo.getDepartmentId();
                Intent iFunc2 = new Intent(mContext, WebActivity.class);
                iFunc2.putExtra("title", title2);
                iFunc2.putExtra("url", url2);
                iFunc2.putExtra("functionback", true);

                iFunc2.putExtra("patientInfoEdit", 2);
                startActivity(iFunc2);
                break;
            case R.id.tv_patientinfo_func3:
                popup_func.dismiss();
                String title3 = getResources().getString(R.string.oldhistory);
                String url3 = UrlAddress.H5_EDITPAST_URL + "&userInfoId=" + patientId + "&departmentId=" + loginInfo.getDepartmentId();
                Intent iFunc3 = new Intent(mContext, WebActivity.class);
                iFunc3.putExtra("title", title3);
                iFunc3.putExtra("url", url3);
                iFunc3.putExtra("functionback", true);

                iFunc3.putExtra("patientInfoEdit", 3);
                startActivity(iFunc3);
                break;
            case R.id.ll_patientinfo_group_title:
                if (groups != null && groups.size() > 0) {
                    if (groupSelectorPopWindow == null) {
                        groupSelectorPopWindow = new GroupSelectorPopWindow(PatientInfoActivity.this, new GroupHorizontalAdapter.onGroupHorizontalClickListener() {
                            @Override
                            public void onClick(int position) {
                                DoctorGroupBean group = groups.get(position);
                                if (!TextUtils.isEmpty(patientInfo.getGroupId())) {
                                    if (patientInfo.getGroupId().equals(group.getGroupId())) {
                                    } else {
                                        newGroupId = group.getGroupId();
                                        loading();
                                        YiJiaHuNetWorkUtils.userJoinDoctorGroup(group.getGroupId(), patientId, handler);
                                    }
                                } else {
                                    newGroupId = group.getGroupId();
                                    loading();
                                    YiJiaHuNetWorkUtils.userJoinDoctorGroup(group.getGroupId(), patientId, handler);
                                }
                            }
                        });
                    }
                    groupSelectorPopWindow.show(ll_title, groups, patientInfo.getGroupId());
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0) {
//                status = data.getIntExtra("status", 0);
//                switch (status) {
//                    case 0:
//                        bt_inhospital.setText(getResources().getString(R.string.inhospital));
//                        break;
//                    case 1:
//                        bt_inhospital.setText(getResources().getString(R.string.outhospital));
//                        break;
//                    case 2:
//                        bt_inhospital.setText(getResources().getString(R.string.havequit));
//                        break;
//                    default:
//                        bt_inhospital.setText(getResources().getString(R.string.inhospital));
//                        break;
//                }
                boolean back = data.getBooleanExtra("finish", false);
                if (back) {
                    finish();
                    return;
                }
                String status = data.getStringExtra("status");
                for (HospitalStatusBean s : hospitalStatus) {
                    if (s.getItemId().equals(status)) {
//                        patientInfo.setstatus?
                        bt_inhospital.setText(s.getName());
                        break;
                    }
                }
            }
        }
    }
}
